package com.hrms.intercept;

import com.hrms.annotation.AdminIgnore;
import com.hrms.entity.Admin;
import com.hrms.service.AdminService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.lang.annotation.Annotation;

@Component
public class AdminInterceptor implements HandlerInterceptor {
    // 管理员端的拦截器

    @Autowired
    private AdminService adminService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Annotation ignore =  handlerMethod.getMethodAnnotation(AdminIgnore.class);
        // 不拦截
        if(ignore != null) {
            return true;
        }

        Admin admin = new Admin();
        admin.setAdmin_id(request.getHeader("Admin-Id"));
        admin.setAdmin_password(request.getHeader("Admin-Password"));
        if(!adminService.passwordisRight(admin)) {
            // 置状态码为401
            System.out.println("401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        return true;
    }
}
